﻿using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Controls;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Public
{
    public class Tools
    {
        #region 初始化表格
        public static void initDataView(DataGridView dataView, string[] cols, string[] names)
        {
            dataView.AllowUserToAddRows = false;
            dataView.AllowUserToDeleteRows = false;
            dataView.AllowUserToOrderColumns = false;
            dataView.AllowUserToResizeRows = false;
            for (int i = 0; i < cols.Length; i++)
            {
                DataGridViewColumn _col = new DataGridViewTextBoxColumn();
                _col.Name = cols[i];
                _col.HeaderText = cols[i];
                _col.ReadOnly = true;
                _col.DataPropertyName = names[i];
                dataView.Columns.Add(_col);
            }
            dataView.AutoGenerateColumns = false;
            dataView.RowsDefaultCellStyle.BackColor = Color.FromArgb(239, 240, 248);//ColorTranslator.FromHtml("#EFF0F8"); ;//隔行变色;
            dataView.AlternatingRowsDefaultCellStyle.BackColor = Color.White;//隔行变色
        }
        #endregion 初始化表格

        /// <summary>
        /// 返回CheckBoxColumn
        /// </summary>
        /// <param name="_name">列名</param>
        /// <param name="_text">列标题显示名称</param>
        /// <returns></returns>
        public static DataGridViewCheckBoxColumn _DataGridViewColumn(string _name, string _text)
        {
            DataGridViewCheckBoxColumn _cl = new DataGridViewCheckBoxColumn();
            _cl.Name = _name;

            //_cl.HeaderCell = new DatagridViewCheckBoxHeaderCell();
            //_cl.HeaderCell.Style =Da
            //_cl.ThreeState = true;
            //DatagridViewCheckBoxHeaderCell cbHeader = new DatagridViewCheckBoxHeaderCell();
            //cbHeader.OnCheckBoxClicked += new CheckBoxClickedHandler(cbHeader_OnCheckBoxClicked(false, _DV));//绑定列标题的勾选事件(全选/取消不选)
            //_cl.HeaderCell = cbHeader;
            //cbHeader.ToolTipText = "全选/取消全选";
            _cl.HeaderText = _text;
            _cl.FalseValue = 0;
            _cl.IndeterminateValue = 0;
            _cl.TrueValue = 1;
            _cl.Width = 50;
            _cl.Frozen = false;
            //this.checkBox1.UseVisualStyleBackColor = true;
            //this.checkBox1.Visible = false;
            // this.checkBox1.Click += new System.EventHandler(this.checkBox1_Click);
            return _cl;
        }

        public static void _添加DataGridViewCheckBoxColumn勾选列(DataGridViewX dataGridViewX_name)
        {
            dataGridViewX_name.Columns.Insert(0, _DataGridViewColumn("check", "选择"));
            dataGridViewX_name.Columns["check"].Visible = true;
            dataGridViewX_name.Columns["check"].Frozen = false;//冻结列
            dataGridViewX_name.Columns["check"].ReadOnly = false;
            dataGridViewX_name.Columns["check"].Width = 35;
        }


        /// <summary>
        ///将二维数组 string[,] Fcell里的列标题字段按顺序装载到DataGridView _dv
        /// </summary>
        /// <param name="_dv">类型：DataGridView</param>
        /// <param name="Fcell">类型：string[][]</param>
        public static void initDataView2(DataGridView _dv, string[,] Fcell, bool ReadOnly = true)
        {
            _dv.DataSource = null;
            // _dv.Columns.Clear();不能直接清除所有列，有些列不是后台加载的（比如反选的列）
            _dv.AllowUserToAddRows = false;
            _dv.AllowUserToDeleteRows = false;
            _dv.AllowUserToOrderColumns = true;
            _dv.AllowUserToResizeRows = false;

            for (int i = 0; i < Fcell.GetLength(0); i++)
            {
                //根据数据库的表的列字段进行装载列标题
                if (Fcell[i, 0] != null)
                {
                    DataGridViewColumn _col = new DataGridViewTextBoxColumn();
                    _col.Name = Fcell[i, 0];
                    _col.HeaderText = Fcell[i, 1];
                    _col.ReadOnly = ReadOnly;
                    _col.DataPropertyName = Fcell[i, 0];

                    _col.SortMode = DataGridViewColumnSortMode.Automatic;
                    _dv.Columns.Add(_col);
                }

            }
            _dv.AutoGenerateColumns = false;  //让它不自己产生多余的列
            _dv.RowsDefaultCellStyle.BackColor = Color.LightGray;//隔行变色
            _dv.AlternatingRowsDefaultCellStyle.BackColor = Color.White;//隔行变色
            _dv.GridColor = Color.SlateGray;
            _dv.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;//列显示字段模式
        }




        #region 系统提示框
        public static void ShowError(string message)
        {
          
            MessageBoxEx.Show(message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }
        public static void ShowWaring(string message)
        {
           
            MessageBoxEx.Show(message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
        public static void ShowInformation(string message)
        {
           
            MessageBoxEx.Show(message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }
        #endregion

        #region DataGridView转DataTable
        public static DataTable GetDgvToTable(DataGridView dgv)
        {
            DataTable dt = new DataTable();

            // 列强制转换
            for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc = new DataColumn(dgv.Columns[count].HeaderText.ToString());
                dt.Columns.Add(dc);
            }

            // 循环行
            for (int count = 0; count < dgv.Rows.Count; count++)
            {
                DataRow dr = dt.NewRow();
                for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                {
                    dr[countsub] = Convert.ToString(dgv.Rows[count].Cells[countsub].Value);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

        #endregion

        public static string FormatDateTime(DateTime value)
        {
            try
            {
                return value.ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception)
            {
                throw;
            }


        }


        #region 条码规则校验
        public static bool CheckBarcodeByRule(string scan_SN, string Rule_SN, out string reson)
        {
            //var reson1 = "";
            if (string.IsNullOrEmpty(scan_SN))
            {
                reson = "扫描条码不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(Rule_SN))
            {
                reson = "条码规则设定不能为空";
                return false;
            }
            if (scan_SN.Length != Rule_SN.Length)
            {
                reson = "条码长度不对，请检查条码校验规则的维护是否正确, \r\n扫描的是：" + scan_SN + "\r\n规则设定：" + Rule_SN;
                return false;
            }
            for (int i = 0; i < Rule_SN.Length; i++)
            {
                if (Rule_SN[i].ToString() != "*")
                {
                    if (scan_SN.ToString()[i].ToString() != Rule_SN[i].ToString())
                    {
                        string s = "条码第" + (i + 1).ToString() + "位字符不正确！\r\n扫描的是：" + scan_SN + "\r\n规则设定：" + Rule_SN;
                        reson = s;
                        return false;
                    }
                }
            }
            reson = "";
            return true;
        }
        #endregion
        #region 导出Excel
        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="dataGridViewX"></param>
        public static void Export_Excel(DataGridViewX dataGridViewX, string Text, bool CheckEmpty = true)
        {
            //权限预判....
            if (CheckEmpty)
            {
                if (dataGridViewX.Rows.Count <= 0)
                {
                    MessageBox.Show("无数据，不能导出");
                    return;
                }
            }

            //if (dataGridViewX.Rows.Count >= 65000)
            //{
            //    MessageBox.Show("行数超过65000行，Excel 2003最大行数为65535，请分批次导出或联系开发商获取支持Excel 2007以上版本", Text);
            //    return;
            //}

            string saveFile, title;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.FileName = Text + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".xls";

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                saveFile = saveFileDialog1.FileName;
                title = saveFileDialog1.Title;

                saveFileDialog1.Filter = "Excel文件（*.xls）|*.xls";//设置文件类型 
                saveFileDialog1.FilterIndex = 1;//设置默认文件类型显示顺序
                                                //ExportReport Excel_daochu = ExportReport.INSTANCE();
                                                //Excel_daochu.ExportExcel(GetDgvToTable(dataGridViewX), saveFile.ToString(), "数据明细");
                System.Diagnostics.Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start(); //  开始监视代码运行时间
                                   //  需要测试的代码 ....
                ExcelHelperForNPOI.TableToExcel(GetDgvToTable(dataGridViewX), saveFile.ToString());
                stopwatch.Stop(); //停止监视
                TimeSpan timespan = stopwatch.Elapsed; //  获取当前实例测量得出的总时间
                double seconds = timespan.TotalSeconds;  //  总秒数
                string File_name = saveFileDialog1.FileName.Substring(saveFileDialog1.FileName.LastIndexOf("\\") + 1);
                ShowInformation("文件：" + File_name + " ]  导出成功! \r\n" +
                "行项：[" + dataGridViewX.RowCount + "]行 \r\n" +
                "位置：[" + saveFileDialog1.FileName.Substring(0, saveFileDialog1.FileName.LastIndexOf("\\")) + "] \r\n" +
                "用时：[" + seconds.ToString("f2") + "]秒");
            }
            else
            { return; }
        }
        #endregion

    }
}
